package net

import (
	"sync"

	"github.com/gorilla/websocket"
)

type GorillaConnectionManager struct {
	Conns  map[*websocket.Conn]string
	lock *sync.Mutex
}

func NewGorillaManager() *GorillaConnectionManager {
	manager := GorillaConnectionManager{
		Conns:  make(map[*websocket.Conn]string),
		lock: &sync.Mutex{},
	}

	return &manager
}

func (manager *GorillaConnectionManager) HasConn(conn *websocket.Conn) bool {
	_, ok := manager.Conns[conn]
	return ok
}

func (manager *GorillaConnectionManager) AddConn(uid string, conn *websocket.Conn) {
	manager.lock.Lock()
	manager.Conns[conn] = uid
	manager.lock.Unlock()
}

func (manager *GorillaConnectionManager) DelConn(uid string, conn *websocket.Conn) {
	manager.lock.Lock()
	delete(manager.Conns, conn)
	manager.lock.Unlock()
}

func (manager *GorillaConnectionManager) GetUid(conn *websocket.Conn) string {
	if uid, ok := manager.Conns[conn]; ok {
		return uid
	}

	return ""
}
